package DAO;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import TO.EdicaoTO;
import util.HibernateUtil;



public class EdicaoDAO {
	
	public EdicaoDAO(){
	}
	
	public static boolean inserir(EdicaoTO edicao) {
			
		try {
			Session sessao = HibernateUtil.getSession();
						
			Transaction transaction = sessao.beginTransaction();
			sessao.save(edicao);
			
			transaction.commit();
			sessao.close();
			
			return true;
			
		} catch(Exception e){
			System.out.println(e.getMessage());
			return false;
		}		
	}
	
	public static boolean atualizar(EdicaoTO edicao) {
		
		try {
			Session sessao = HibernateUtil.getSession();
						
			Transaction transaction = sessao.beginTransaction();
			sessao.update(edicao);
			
			transaction.commit();
			sessao.close();
			
			return true;
			
		} catch(Exception e){
			System.out.println(e.getMessage());
			return false;
		}		
	}
	
	public static boolean deletar(EdicaoTO edicao) {
		
		try {
			Session sessao = HibernateUtil.getSession();
						
			Transaction transaction = sessao.beginTransaction();
			sessao.delete(edicao);
			
			transaction.commit();
			sessao.close();
			
			return true;
			
		} catch(Exception e){
			System.out.println(e.getMessage());
			return false;
		}		
	}
	
	/**
	 * 
	 * @param cod_livro
	 * @return
	 */
	public static List<EdicaoTO>  consultar(int cod_livro){
		 
		List<EdicaoTO> lista = new ArrayList<EdicaoTO>(); 
		try {
			Session session = HibernateUtil.getSession();  
		    
		    lista = session.createQuery("from EdicaoTO where livro = ?")
	    	.setInteger(0, cod_livro)
	    	.list();
			
		    session.close();
			
		} catch(Exception e)
			{System.out.println(e.getMessage());
		}
		
		return lista;
	}
	
	public static EdicaoTO  consultarEdicao(int num_edicao, int cod_livro){
		 
		List<EdicaoTO> lista = new ArrayList<EdicaoTO>();
		EdicaoTO edicao = null;
		try {
			Session session = HibernateUtil.getSession();  
		    
		    lista = session.createQuery("from EdicaoTO where num_edicao = ? and livro = ?")
	    	.setInteger(0, num_edicao)
	    	.setInteger(1, cod_livro)
	    	.list();
			
		    session.close();
		    
		    edicao = lista.get(0);
			
		} catch(Exception e)
			{System.out.println(e.getMessage());
		}
		
		return edicao;
	}
	
	public static List<EdicaoTO>  consultarISBN(String isbn_livro){
		String isbn = "%"+isbn_livro+"%";
		List<EdicaoTO> lista = new ArrayList<EdicaoTO>(); 
		try {
			Session session = HibernateUtil.getSession();  
		    
		    lista = session.createQuery("from EdicaoTO where isbn like ?")
	    	.setString(0, isbn)
	    	.list();
			
		    session.close();
			
		} catch(Exception e)
			{System.out.println(e.getMessage());
		}
		
		return lista;
	}

}
